package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Conversation;
import com.woyao.core.model.GetMessageResponse;
import com.woyao.core.model.Talk;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

public class TalkActivity extends AppCompatActivity {
    ProgressDialog progressDialog;

    private LinearLayout talkView;

    private EditText content;
    private Button sendButton;
    private List<Talk> talks ;
    private  Integer mid ;
    private ScrollView chatScroll ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_talk);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        chatScroll = (ScrollView)findViewById(R.id.chat_scroll);

        content = (EditText)findViewById(R.id.talk_content);



        sendButton  = (Button) findViewById(R.id.send_talk);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendTalk();
            }
        });
        Intent intent = getIntent();
        mid = intent.getIntExtra("mid",0);

        talkView=(LinearLayout)findViewById(R.id.chat_list);



        loadTalks();
        sendButton.requestFocus();


    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void loadTalks() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();


        AsyncTask<Void, Void, GetMessageResponse> task = new AsyncTask<Void, Void, GetMessageResponse>() {
            @Override
            protected GetMessageResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMessageResponse> responseCall = svc.getMessage(WoyaoooApplication.userId, mid);
                try {
                    GetMessageResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(final GetMessageResponse response) {
                progressDialog.dismiss();
                if (response != null ) {
                    render( response );
                } else {
                    Common.showSnack(TalkActivity.this,sendButton,"网络错误，请重试");
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }

    private  void render(GetMessageResponse tr ){

        Conversation cur = tr.getContent();
        this.setTitle( cur.getTitle() );


        talks = cur.getTalks();
        talkView.removeAllViews();
        for(Talk talk : talks){
            addOneTalk( talk );
        }
        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
    }


    private void addOneTalk( Talk talk ){

        View convertView;
        if  (talk.getUser_id().equals(WoyaoooApplication.userId) )
        {
            convertView=  LayoutInflater.from(TalkActivity.this).inflate( R.layout.activity_user_talk, null);
            TextView thename = (TextView)convertView.findViewById( R.id.user_name  );
            TextView thecontent = (TextView)convertView.findViewById( R.id.user_description  );
            TextView thedate = (TextView)convertView.findViewById( R.id.user_date  );
            CircleImageView thesnailview = (CircleImageView)convertView.findViewById( R.id.user_snailview  );
            thename.setText(talk.getDisplayname());
            thecontent.setText(talk.getDescription());
            thedate.setText(talk.getCreated());
            Picasso.with(this)
                    .load(talk.getSnailview())
                    .into(thesnailview );

        }else{
            convertView= LayoutInflater.from(TalkActivity.this).inflate( R.layout.activity_relation_talk, null);
            TextView thename = (TextView)convertView.findViewById( R.id.relation_name  );
            TextView thecontent = (TextView)convertView.findViewById( R.id.relation_description  );
            TextView thedate = (TextView)convertView.findViewById( R.id.relation_date  );
            CircleImageView thesnailview = (CircleImageView)convertView.findViewById( R.id.relation_snailview  );
            thename.setText(talk.getDisplayname());
            thecontent.setText(talk.getDescription());
            thedate.setText(talk.getCreated());
            Picasso.with(this)
                    .load(talk.getSnailview())
                    .into(thesnailview );

        }


        talkView.addView(convertView);
    }

    private void showOneTalk( String  desc ){
        SimpleDateFormat formatter   =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate   =   new Date(System.currentTimeMillis());//获取当前时间
        String   strDate   =   formatter.format(curDate);

        Talk newTalk = new Talk();
        newTalk.setCreated(strDate );
        newTalk.setUser_id( WoyaoooApplication.userId);
        newTalk.setDescription(  desc);
        talks.add( newTalk );
        addOneTalk( newTalk );

        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
    }

    private void sendTalk() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("发送消息······");
        progressDialog.show();


        final String desc = content.getText().toString();
        if (desc.equals("")) return;



        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.talk(WoyaoooApplication.userId, mid,desc);
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                progressDialog.dismiss();
                if (success) {
                    showOneTalk(   desc );

                    content.setText("");

                } else {
                    Common.showSnack(TalkActivity.this,sendButton,"网络错误，请重试");
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }




}
